package com.education.ai.controller;

import com.education.ai.entity.Exercise;
import com.education.ai.service.ExerciseService;
import com.education.ai.model.ExerciseRequest;
import com.education.ai.service.AiTeachingService;
import com.education.ai.util.TeacherContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 练习题控制器
 */
@RestController
@Slf4j
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true")  // 添加跨域支持
@RequestMapping("/api/exercises")
public class ExerciseController {

    @Autowired
    private ExerciseService exerciseService;
    
    @Autowired
    private AiTeachingService aiTeachingService;

    /**
     * 基础练习题接口
     */
    @GetMapping
    public List<Exercise> getAllExercises() {
        return exerciseService.getAllExercises();
    }

    /**
     * 根据ID获取练习题
     */
    @GetMapping("/{id}")
    public ResponseEntity<Exercise> getExerciseById(@PathVariable Long id) {
        Exercise exercise = exerciseService.getExerciseById(id);
        if (exercise != null) {
            return ResponseEntity.ok(exercise);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建练习题
     */
    @PostMapping
    public Exercise createExercise(@RequestBody Exercise exercise) {
        return exerciseService.saveExercise(exercise);
    }

    /**
     * 更新练习题
     */
    @PutMapping("/{id}")
    public ResponseEntity<Exercise> updateExercise(@PathVariable Long id, @RequestBody Exercise exercise) {
        Exercise existingExercise = exerciseService.getExerciseById(id);
        if (existingExercise == null) {
            return ResponseEntity.notFound().build();
        }
        
        exercise.setId(id);
        Exercise updatedExercise = exerciseService.saveExercise(exercise);
        return ResponseEntity.ok(updatedExercise);
    }

    /**
     * 删除练习题
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteExercise(@PathVariable Long id) {
        Exercise existingExercise = exerciseService.getExerciseById(id);
        if (existingExercise == null) {
            return ResponseEntity.notFound().build();
        }
        
        exerciseService.deleteExercise(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 根据学科获取练习题
     */
    @GetMapping("/subject/{subject}")
    public List<Exercise> getExercisesBySubject(@PathVariable String subject) {
        return exerciseService.getExercisesBySubject(subject);
    }

    /**
     * 根据年级获取练习题
     */
    @GetMapping("/grade/{grade}")
    public List<Exercise> getExercisesByGrade(@PathVariable String grade) {
        return exerciseService.getExercisesByGrade(grade);
    }

    /**
     * 根据学科和年级获取练习题
     */
    @GetMapping("/subject/{subject}/grade/{grade}")
    public List<Exercise> getExercisesBySubjectAndGrade(
            @PathVariable String subject,
            @PathVariable String grade) {
        return exerciseService.getExercisesBySubjectAndGrade(subject, grade);
    }

    /**
     * 根据学科、年级和主题获取练习题
     */
    @GetMapping("/subject/{subject}/grade/{grade}/topic/{topic}")
    public List<Exercise> getExercisesBySubjectGradeAndTopic(
            @PathVariable String subject,
            @PathVariable String grade,
            @PathVariable String topic) {
        return exerciseService.getExercisesBySubjectAndGradeAndTopic(subject, grade, topic);
    }

    /**
     * 生成练习题
     */
    @PostMapping("/generate")
    public ResponseEntity<List<Map<String, Object>>> generateExercises(
            @RequestParam String subject,
            @RequestParam String grade,
            @RequestParam String topic,
            @RequestParam(defaultValue = "5") int count) {
        try {
            List<Map<String, Object>> exercises = exerciseService.generateExercises(subject, grade, topic, count)
                    .stream()
                    .map(exercise -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", exercise.getId());
                        map.put("subject", exercise.getSubject());
                        map.put("grade", exercise.getGrade());
                        map.put("topic", exercise.getTopic());
                        map.put("questionType", exercise.getQuestionType());
                        map.put("content", exercise.getContent());
                        map.put("answer", exercise.getAnswer());
                        map.put("analysis", exercise.getAnalysis());
                        map.put("difficulty", exercise.getDifficulty());
                        map.put("createdTime", exercise.getCreatedTime());
                        return map;
                    })
                    .collect(Collectors.toList());
            return ResponseEntity.ok(exercises);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            List<Map<String, Object>> errorList = new ArrayList<>();
            errorList.add(errorMap);
            return ResponseEntity.badRequest().body(errorList);
        }
    }
    
    /**
     * 根据学习阶段获取对应的年级
     */
    private String getGradeFromStage(String stage) {
        if (stage == null) {
            return "小学";
        }
        
        switch (stage) {
            case "primary":
                return "小学";
            case "junior":
                return "初中";
            case "senior":
                return "高中";
            default:
                return stage;
        }
    }
    
    /**
     * 生成课后习题 - 符合前端接口
     */
    @PostMapping("/homework/after-class/generate")
    public ResponseEntity<Map<String, Object>> generateAfterClassExercises(@RequestBody Map<String, Object> requestBody) {
        try {
            String stage = (String) requestBody.get("stage");
            String subject = (String) requestBody.get("subject");
            String textbook = (String) requestBody.get("textbook");
            String chapter = (String) requestBody.get("chapter");
            Integer questionCount = Integer.valueOf(requestBody.get("questionCount").toString());
            List<String> questionTypes = (List<String>) requestBody.get("questionTypes");
            
            // 获取教师ID - 首先尝试从请求体获取
            String teacherId = (String) requestBody.get("teacher_id");
            
            // 如果请求体中没有教师ID，则从当前登录用户上下文获取
            if (teacherId == null || teacherId.isEmpty()) {
                teacherId = TeacherContext.getCurrentTeacherId();
                log.info("从当前登录上下文获取到教师ID: {}", teacherId);
            }
            
            if (stage == null || subject == null || questionCount == null || questionTypes == null) {
                return ResponseEntity.badRequest().build();
            }
            
            // 调用带教师ID的生成方法
            List<Exercise> generatedExercises = exerciseService.generateExercises(
                stage, subject, textbook, chapter, questionCount, questionTypes, teacherId);
            
            // 将Exercise转换为前端期望的格式
            List<Map<String, Object>> formattedExercises = exerciseService.formatExercisesForFrontend(
                generatedExercises, questionTypes);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", formattedExercises);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("生成课后习题失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "生成习题失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 保存课后习题
     */
    @PostMapping("/homework/after-class/save")
    public ResponseEntity<Map<String, Object>> saveAfterClassExercises(@RequestBody Map<String, Object> requestBody) {
        try {
            String stage = (String) requestBody.get("stage");
            String subject = (String) requestBody.get("subject");
            String textbook = (String) requestBody.get("textbook");
            String chapter = (String) requestBody.get("chapter");
            List<Map<String, Object>> questions = (List<Map<String, Object>>) requestBody.get("questions");
            
            // 获取教师ID - 首先尝试从请求体获取
            String teacherId = (String) requestBody.get("teacher_id");
            
            // 如果请求体中没有教师ID，则从当前登录用户上下文获取
            if (teacherId == null || teacherId.isEmpty()) {
                teacherId = TeacherContext.getCurrentTeacherId();
                log.info("从当前登录上下文获取到教师ID: {}", teacherId);
            }
            
            if (stage == null || subject == null || questions == null) {
                return ResponseEntity.badRequest().build();
            }
            
            // 调用带教师ID的保存方法
            List<Exercise> savedExercises = exerciseService.saveExercisesFromFrontend(
                subject, stage, chapter, textbook, questions, teacherId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", savedExercises);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("保存课后习题失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "保存习题失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 获取热点考题
     */
    @GetMapping("/homework/hot")
    public ResponseEntity<Map<String, Object>> getHotExercises(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String stage,
            @RequestParam(required = false) String subject,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            List<Map<String, Object>> exercises = exerciseService.getHotExercises(
                page, pageSize, stage, subject, startDate, endDate);
            
            int total = exerciseService.countHotExercises(stage, subject, startDate, endDate);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", exercises);
            response.put("total", total);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取热点考题失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取热点考题失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 获取高频错题
     */
    @GetMapping("/homework/mistakes")
    public ResponseEntity<Map<String, Object>> getMistakes(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String stage,
            @RequestParam(required = false) String subject,
            @RequestParam(required = false) String mistakeType) {
        try {
            List<Map<String, Object>> mistakes = exerciseService.getMistakes(
                page, pageSize, stage, subject, mistakeType);
            
            int total = exerciseService.countMistakes(stage, subject, mistakeType);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", mistakes);
            response.put("total", total);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取高频错题失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取高频错题失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getExerciseHistory(
            @RequestParam(required = false) String teacherId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size) {
        try {
            // 如果未提供teacherId，则从当前登录用户上下文获取
            if (teacherId == null || teacherId.isEmpty()) {
                teacherId = TeacherContext.getCurrentTeacherId();
                log.info("从当前登录上下文获取到教师ID: {}", teacherId);
            }

            if (teacherId == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "未提供教师ID且无法从上下文获取");
                errorResponse.put("data", null);
                return ResponseEntity.badRequest().body(errorResponse);
            }

            List<Map<String, Object>> history = exerciseService.getExerciseHistory(teacherId, page, size);
            
            // 提取总记录数
            long total = 0;
            if (!history.isEmpty() && history.get(0).containsKey("total")) {
                total = (long) history.get(0).remove("total");
            }
            
            // 如果只有一个记录且只包含total字段，则清空结果列表
            if (history.size() == 1 && history.get(0).size() == 1 && history.get(0).containsKey("total")) {
                history.clear();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", history);
            response.put("total", total);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取历史记录失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取历史记录失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

} 